package com.suxin.test.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/14 17:10
 */
@Slf4j
public class EcoHttpServer {

    public static void main(String[] args) throws Exception{
        EcoHttpServer ecoServer = new EcoHttpServer();
        log.info("服务启动! start...");
        ecoServer.start();
    }

    private void start() throws Exception{

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ChannelFuture future = serverBootstrap
                    .group(bossGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress("127.0.0.1", 9999))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.info("EcoHttpServer initChannel...");
                            ch.pipeline()
                                    .addLast(new HttpServerCodec())
                                    .addLast("aggregator", new HttpObjectAggregator(10*1024*1024))
                                    /*把应答报文 压缩,非必要*/
                                    .addLast("compressor",new HttpContentCompressor())
                                    .addLast(new EcoHttpInChannelHandler())
                            ;
                        }
                    })
                    .bind().sync();
            log.info("server 端口绑定完成! bind...");
            future.channel().closeFuture().sync();
            log.info("server close!...");
        } finally {
            bossGroup.shutdownGracefully().sync();
        }
    }

}
